<template>
  <div class="app-container">
    <h2 class="form-title">🎓 发布新课程</h2>

    <el-steps :active="1" process-status="process" align-center class="steps-container">
      <el-step title="填写课程信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

    <el-form label-width="120px" class="course-form" :model="courseInfo">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder="例如：Java 后端开发实战" clearable/>
      </el-form-item>

      <el-form-item label="课程分类">
        <el-cascader v-model="subjectIds" :options="subjectOptions"
                     :props="{ checkStrictly: true, value: 'id', label: 'title' }" placeholder="请选择课程分类"
                     clearable
        />
      </el-form-item>

      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择讲师" clearable>
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number v-model="courseInfo.lessonNum" :min="0" controls-position="right" placeholder="请输入总课时"/>
      </el-form-item>

      <el-form-item label="课程简介">
        <div class="editor-container">
          <Toolbar class="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig"/>
          <Editor class="editor-content" v-model="courseInfo.description" :defaultConfig="editorConfig"
                  @onCreated="onEditorCreated"
          />
        </div>
      </el-form-item>

      <el-form-item label="课程封面">
        <el-upload class="avatar-uploader" action="http://localhost:8000/admin/oss/upload" :show-file-list="false"
                   :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
        >
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar"/>
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div class="upload-text">上传课程封面</div>
            <div class="upload-hint">推荐尺寸：800×450，JPG/PNG 格式</div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number v-model="courseInfo.price" :min="0" controls-position="right" placeholder="请输入价格"/>
        <span class="price-suffix">元</span>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :disabled="saveBtnDisabled" @click="saveOrUpdate" class="submit-btn">保存并下一步
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import course from '@/api/edu/course'
import { getCategoryList } from '@/api/edu/subject'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

const defaultForm = {
  title: '',
  subjectParentId: '',
  subjectId: '',
  teacherId: '',
  lessonNum: 0,
  description: '',
  cover: '',
  price: 0
}

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      courseInfo: { ...defaultForm },
      teacherList: [],
      subjectParentList: [],
      saveBtnDisabled: false,
      subjectIds: [],
      editor: null,
      courseId: '',
      toolbarConfig: {
        excludeKeys: ['uploadVideo', 'group-video']
      },
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: 'http://localhost:9001/eduoss/upload/avatar',
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024,
            allowedFileTypes: ['image/jpeg', 'image/png'],
            onSuccess(file, res) {
              console.log('上传成功', res)
            },
            onFailed(file, res) {
              console.error('上传失败', res)
            }
          }
        }
      }
    }
  },
  computed: {
    subjectOptions() {
      return this.subjectParentList.map(parent => ({
        id: parent.id,
        title: parent.name,
        children: parent.children
      }))
    }
  },
  created() {
    // this.getTeacherList()
    // this.getSubjectParent()

    //获取路由id值,回显数据
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id
      //调用根据id查询课程的方法
      this.getCourseInfo()
    } else {
      //初始化courseInfo
      // this.courseInfo = {}//先清空...
      //初始化一级分类
      this.getSubjectParent()
    }
    //初始化讲师列表
    this.getTeacherList()
  },
  methods: {
    //根据课程id查询,回显数据
    getCourseInfo() {
      course.getCourseInfo(this.courseId)
        .then(response => {
          this.courseInfo = response.data

          // 👇 加上这行，让课程分类回显
          this.subjectIds = [this.courseInfo.subjectParentId, this.courseInfo.subjectId]

          // 加载分类列表（防止下拉为空）
          this.getSubjectParent()
        })
    },
    getTeacherList() {
      course.getTeacherList().then(res => {
        this.teacherList = res.data
      })
    },
    getSubjectParent() {
      getCategoryList().then(res => {
        this.subjectParentList = res.data
      })
    },
    saveOrUpdate() {
      if (this.subjectIds.length) {
        this.courseInfo.subjectParentId = this.subjectIds[0]
        this.courseInfo.subjectId = this.subjectIds[1]
      }

      this.saveBtnDisabled = true // 防止重复提交

      if (this.courseId) {
        // 如果有 courseId，说明是修改
        this.courseInfo.id = this.courseId // 补上 id 字段
        course.updateCourseInfo(this.courseInfo).then(res => {
          this.$message.success('修改课程成功！')
          this.$router.push({ path: '/subject/chapter/' + this.courseId })
        }).finally(() => {
          this.saveBtnDisabled = false
        })
      } else {
        // 没有 courseId，说明是新增
        course.saveCourseInfo(this.courseInfo).then(res => {
          this.$message.success('添加课程成功！')
          this.$router.push({ path: '/subject/chapter/' + res.data.courseId })
        }).finally(() => {
          this.saveBtnDisabled = false
        })
      }
    },

    // 配置
    onEditorCreated(editor) {
      this.editor = editor
    },
    beforeDestroy() {
      if (this.editor) {
        this.editor.destroy()
        this.editor = null
      }
    },
    handleAvatarSuccess(res) {
      this.courseInfo.cover = res.data
    },
    beforeAvatarUpload(file) {
      const isValid = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isValid) this.$message.error('仅支持 JPG/PNG 格式图片！')
      if (!isLt2M) this.$message.error('图片大小不能超过 2MB！')
      return isValid && isLt2M
    }
  }
}
</script>

<style scoped>
.app-container {
  max-width: 960px;
  margin: 0 auto;
  padding: 30px;
  background: #f9f9f9;
}

.form-title {
  text-align: center;
  font-size: 28px;
  margin-bottom: 30px;
  background: -webkit-linear-gradient(45deg, #409eff, #66b1ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: bold;
}

.steps-container {
  margin-bottom: 40px;
}

.course-form {
  background: #fff;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.el-form-item {
  margin-bottom: 24px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.editor-content {
  min-height: 260px;
  margin-top: -10px;
  margin-left: 10px;
  background: #fff;
}

.avatar-uploader {
  width: 100%;
  max-width: 400px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
  background-color: #fdfdfd;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.upload-placeholder {
  text-align: center;
  color: #909399;
}

.avatar-uploader-icon {
  font-size: 28px;
  margin-bottom: 6px;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.upload-hint {
  font-size: 12px;
  color: #c0c4cc;
}

.price-suffix {
  margin-left: 10px;
  color: #606266;
}

.submit-btn {
  width: 220px;
  height: 40px;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

@media (max-width: 768px) {
  .app-container {
    padding: 20px;
  }

  .editor-content {
    min-height: 200px;
  }

  .submit-btn {
    width: 100%;
  }
}
</style>
